package encaps.action;

import encaps.entities.Grant;
import encaps.entities.MovieLocal;
import encaps.entities.MovieLocalHome;
import encaps.resources.Labels;
import encaps.utils.EntityUtil;
import encaps.utils.SystemException;
import encaps.utils.XMLHelper;
import java.util.HashMap;
import javax.ejb.FinderException;
import javax.naming.NamingException;
import org.jdom.Element;

public class ViewMovieAction extends Action {

    public static final String VIEW_MOVIE = "viewMovie";
    private Long id;
    private ActionContext actionContext;

    public ViewMovieAction(ActionContext context, Grant requiredGrant) {
        actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {

            MovieLocalHome movieHome = EntityUtil.getMovieHome();
            id = new Long(actionContext.getTextParameter(ID));
            MovieLocal movie = movieHome.findByPrimaryKey(id);
            Element movieElement = XMLHelper.toXMLElement(movie,
                    Labels.getLabel(Labels.VIEW_MOVIE), false,
                    actionContext.getUserLogin(), actionContext.getUserRole(),
                    new HashMap<String, String>());
            return movieElement;

        } catch (NamingException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_FIND_LOCAL_HOME_OBJECT_MESSAGE), ex);
        } catch (FinderException ex) {
            String message = String.format(Labels.getLabel(Labels.MOVIE_NOT_FOUND_MESSAGE_PATTERN), id);
            throw new ActionExecutionException(message, ex);
        } catch (SystemException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        }
    }
}
